package com.mine.seckill.controller;

import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Optional;

@RestController
public class RedissonSaleController {
    private static final String COUNT_KEY = "count";
    private static final String LOCK_KEY = "LOCK";
    @Autowired
    private Redisson redisson;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @RequestMapping(value = "/sale2")
    public void sale() throws InterruptedException {
        RLock lock = redisson.getLock(LOCK_KEY);
        System.out.println(redisson.getConfig().getLockWatchdogTimeout());
        try {
            lock.lock();
            int count = Integer.parseInt(Optional.ofNullable(stringRedisTemplate.opsForValue().get(COUNT_KEY)).orElse("0"));
            if (count > 0) {
                count--;
                // 实现秒杀的业务操作
                Thread.sleep(1000000);
                stringRedisTemplate.opsForValue().set(COUNT_KEY, String.valueOf(count));
            }
        } finally {
            lock.unlock();
        }
    }
}
